<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :class="{ readonly: readOnly }"
      :custom-class="'panna-dialog_medium'"
      :title="title"
      :append-to-body="true"
      :visible="innerDialogFormVisible"
      :before-close="handleClose"
      @closed="closedDialog"
    >
      <el-form
        ref="formData"
        class="base-pipeline-layout system-user-form"
        :model="formData"
        :rules="formDataRules"
        status-icon
        label-width="120px"
      >
        <el-form-item :label="dataList.Account" prop="account">
          <el-input
            v-model="formData.account"
            :disabled="editId > 0"
            :placeholder="dataList.EnterAccount"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item :label="dataList.Name" prop="name">
          <el-input
            v-model="formData.name"
            :disabled="readOnly || resetpwd === 1"
            autocomplete="off"
            maxlength="5"
          ></el-input>
        </el-form-item>

        <el-form-item
          v-if="resetpwd === 1"
          :disabled="readOnly || resetpwd === 1"
          :label="dataList.password"
          prop="password"
        >
          <el-input
            v-model="formData.password"
            type="password"
            :placeholder="dataList.PleaseEnterPassword"
          />
        </el-form-item>

        <el-form-item
          v-if="resetpwd === 1"
          :label="dataList.ConfirmPassword"
          :disabled="readOnly || resetpwd === 1"
          prop="repeatPwd"
        >
          <el-input
            v-model="formData.repeatPwd"
            type="password"
            :placeholder="dataList.PleaseEnterPasswordAgain"
          />
        </el-form-item>

        <el-form-item :label="dataList.department" prop>
          <DepartTreeSelect
            v-model="formData.departmentIds"
            :is-check="true"
            :disabled="readOnly || resetpwd === 1"
            :tree-data="depData"
          />
        </el-form-item>
        <el-form-item :label="dataList.SuperiorLeader" prop="leaders">
          <el-select
            ref="selectDom"
            v-model="formData.leaders"
            :disabled="readOnly || resetpwd === 1"
            multiple
            :placeholder="dataList.PleaseSuperiorLeader"
            filterable
            remote
            reserve-keyword
            :remote-method="remoteUser"
            :loading="searchUserLoading"
            value-key="id"
            @change="changeLeader"
          >
            <el-option
              v-for="item in userList"
              :key="item.id"
              :label="item.name"
              :value="item"
              :disabled="item.status === 0 || resetpwd === 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="dataList.UserGroup" prop="userGroupIds">
          <el-select
            v-model="formData.userGroupIds"
            :disabled="readOnly || resetpwd === 1"
            multiple
            :placeholder="dataList.Pleaseselectusergroup"
          >
            <el-option
              v-for="(item, index) in groupList"
              :key="index"
              :label="item.name"
              :value="item.id"
              :disabled="item.state === 0 || resetpwd === 1"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="dataList.mobile" prop="mobile">
          <el-input
            v-model="formData.mobile"
            :disabled="readOnly || resetpwd === 1"
            autocomplete="off"
            maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item :label="dataList.mail">
          <el-input
            v-model="formData.mail"
            :disabled="readOnly || resetpwd === 1"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          :label="dataList.status"
          :disabled="readOnly"
          prop="userStatus"
        >
          <el-switch
            v-model="formData.userStatus"
            :disabled="readOnly || resetpwd === 1"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item :label="dataList.headPortrait" prop="icon">
          <BaseUpload
            key="BaseUpload"
            ref="BaseUpload"
            v-model="formData.icon"
            :disabled="readOnly || resetpwd === 1"
            business-type="10"
            :file-size="1024"
          />
        </el-form-item>
        <el-form-item :label="dataList.signature" prop="accountSignIcon">
          <BaseUpload
            key="BaseUploadAccountSignIcon"
            ref="BaseUploadAccountSignIcon"
            v-model="formData.accountSignIcon"
            :disabled="readOnly || resetpwd === 1"
            business-type="11"
            :file-size="1024"
          />
        </el-form-item>
        <el-form-item :label="dataList.TestAccount" prop="testAccount">
          <el-select
            v-model="formData.testAccount"
            :disabled="readOnly"
            :placeholder="btn.PleaseSelect"
          >
            <el-option :label="dataList.Yes" :value="1" />
            <el-option :label="dataList.No" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <span
        v-if="!readOnly || resetpwd === 1"
        slot="footer"
        class="base-dialog-footer"
      >
        <el-button
          v-loading="submitLoad"
          type="primary"
          :disabled="submitReadOnly"
          @click="onSubmit('formData')"
          >{{ btn.Save }}</el-button
        >
        <el-button @click="handleClose">{{ btn.Cancel }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  userDetail,
  getUserListNoPage,
} from "../../../api/Permission/PermissionUser.js";
import { departmentTree } from "../../../api/Permission/PermissionDepartment.js";
import { GetUserGroupList } from "../../../api/Permission/PermissionUserGroup.js";
import { formatData } from "../../../utils/index";
import { validatePass } from "@/utils/validate";

import DepartTreeSelect from "../../../components/Permission/DepartTreeSelect.vue"; // 多选树形下拉
export default {
  name: "PermissionUserEdit",
  components: { DepartTreeSelect },
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
    resetpwd: {
      type: Number,
      default: 0,
    },
  },
  data() {
    return {
      loading: false,
      submitLoad: false,
      searchUserLoading: false,
      title: "",
      innerDialogFormVisible: false,
      formData: {
        id: 0,
        account: "",
        password: "123456",
        repeatPwd: "123456",
        name: "",
        mobile: "",
        mail: "",
        salt: "",
        icon: "",
        accountSignIcon: "",
        userStatus: 1,
        leaders: [],
        departmentIds: [],
        userGroupIds: "",
        testAccount: 0,
      },
      radio: true,
      level: -1,
      depData: [],
      // departmentList: [],
      // departmentNumber: [],
      userList: [],
      groupList: [],
      originUserData: {},

      formDataRules: {
        // 新增时的规则
        account: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        repeatPwd: [
          {
            required: true,
            message: this.$t(
              "Permission.PermissionUser.PleaseEnterPasswordAgain"
            ),
          },
          { validator: this.checkPwd, trigger: "blur" },
          { required: true, validator: validatePass, trigger: "blur" },
        ],
        name: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        departmentIds: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        // leaders: [
        //   {
        //     required: true,
        //     trigger: "blur",
        //     validator: this.Helper.validateFunction,
        //   },
        // ],
        mobile: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        mail: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      submitReadOnly: false,
    };
  },
  computed: {
    btn() {
      return this.$t("Permission.buttons");
    },
    dataList() {
      return this.$t("Permission.PermissionUser");
    },
  },
  watch: {
    value() {
      this.innerDialogFormVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  created() {},
  beforeDestroy() {
    this.handleClose();
  },
  methods: {
    async init() {
      if (this.resetpwd === 1) {
        this.title = this.$t("Permission.PermissionUser.ChangePassword");
      } else {
        this.title = this.readOnly
          ? this.$t("Permission.buttons.Look")
          : this.editId
            ? this.$t("Permission.buttons.Edit")
            : this.$t("Permission.buttons.Add");
      }
      this.loading = true;
      // this.level = await this.getLevel();
      await departmentTree()
        .then((res) => {
          if (res.data.length) {
            var data = (res.data || []).map((x) => {
              x.name = this.$i18n.locale === "en" ? x.eName : x.name;
              return x;
            });
            // if (Number(this.level) > 0) {
            //   data = this.setTreeData(data);
            //   this.radio = false;
            // } else {
            //   this.radio = true;
            // }
            this.depData = formatData(data);
          }
        })
        .catch(() => {
          this.loading = false;
        });

      GetUserGroupList({ pageIndex: 1, pageSize: 9999 }).then((res) => {
        this.groupList = (res?.data?.dataList || []).map((x) => {
          x.name = this.$i18n.locale === "en" ? x.eName : x.name;
          return x;
        });
      });
      if (this.editId) {
        userDetail({ id: this.editId })
          .then((res) => {
            this.loading = false;
            const {
              id,
              account,
              name,
              userStatus,
              mobile,
              mail,
              salt,
              gmpAuth,
              accountType,
              testAccount,
            } = res.data;
            this.originUserData = res.data;
            this.formData = {
              id,
              account,
              name,
              userStatus,
              mobile,
              mail,
              salt,
              gmpAuth,
              // icon: `${this.$baseProtocol}//${res.data.fileDomain}/${res.data.fileBucket}/${res.data.icon}`,
              // accountSignIcon: `${this.$baseProtocol}//${res.data.fileDomain}/${res.data.fileBucket}/${res.data.accountSignIcon}`,
              icon: `${res.data.icon}`,
              accountSignIcon: `${res.data.accountSignIcon}`,
              accountType,
              // departmentIds: res.data.departmentIds,
              departmentIds:
                res.data.departmentIds && res.data.departmentIds.split(","),
              userGroupIds:
                res.data.userGroupIds && res.data.userGroupIds.split(","),
              leaders: res.data.leaders,
              testAccount,
            };

            res.data.leaders.forEach((item) => {
              const temp = {
                currentLabel: item.name,
                currentValue: {
                  id: item.id,
                  name: item.name,
                },
                label: item.name,
                value: {
                  id: item.id,
                  name: item.name,
                },
              };
              this.$refs.selectDom.cachedOptions.push(temp);
            });
          })
          .catch(() => {
            this.loading = false;
          });
      } else {
        this.loading = false;
      }
    },
    // async getLevel() {
    //   return new Promise((resolve) => {
    //     getConfigByKey("DepartsLevel", 0).then((res) => {
    //       resolve(res.data ? res.data[0].value : "0");
    //     });
    //   });
    // },
    setTreeData(data) {
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          data[i].children.forEach((element) => {
            if (element.children) {
              element.children = undefined;
            }
          });
        }
      }

      return data;
    },

    onSubmit() {
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.submitReadOnly = true;
          const requestData = JSON.parse(JSON.stringify(this.formData));
          // 用户组
          if (requestData.userGroupIds) {
            requestData.userGroupIds = requestData.userGroupIds.join(",");
          }
          if (requestData.departmentIds) {
            requestData.departmentIds = requestData.departmentIds.join(",");
          }

          requestData.icon = this.$refs.BaseUpload.filePath
            ? this.$refs.BaseUpload.filePath
            : this.originUserData.icon;
          requestData.accountSignIcon = this.$refs.BaseUploadAccountSignIcon
            .filePath
            ? this.$refs.BaseUploadAccountSignIcon.filePath
            : this.originUserData.accountSignIcon;
          // console.log(requestData);
          if (!this.editId) {
            this.addAPI(requestData);
          } else {
            this.editAPI(requestData);
          }
        } else {
          return false;
        }
      });
    },
    // 新增接口
    addAPI(data) {
      create(data)
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
          this.loading = false;
          this.submitReadOnly = false;
        });
    },
    // 编辑接口
    editAPI(data) {
      update({
        ...data,
        id: this.editId,
      })
        .then((res) => {
          // 判断是当前用户的话更新头像
          if (this.editId === this.$store.getters.currentUserId) {
            this.$store.commit("user/SET_HEADIMG", data.icon);
          }
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
          this.loading = false;
          this.submitReadOnly = false;
        });
    },
    // 操作成功回调用
    SuccessfulOperation() {
      this.submitLoad = false;
      this.submitReadOnly = false;
      this.$emit("success");
      this.handleClose();
    },

    checkDepart(node, index) {
      this.$delete(this.formData.departmentIds, index);
      this.formData.departmentIds.push(node.id);
    },

    // 关闭弹框
    handleClose() {
      this.$emit("input", false);
    },
    // 关闭弹框动画结束
    closedDialog() {
      // 动画结束后在清空表单 防止页面闪烁
      this.$refs.formData.resetFields();
      // this.departmentList = [];
      // this.departmentNumber = [];
      this.$emit("input", false);
      this.$parent.getList();
      this.$parent.resetpwd = 0;
    },
    // 校验二次密码
    checkPwd(rule, value, callback) {
      if (value.length < 15) {
        callback(
          new Error(this.$t("Permission.PermissionUser.Password15Characters"))
        );
      } else if (value === "") {
        callback(
          new Error(
            this.$t("Permission.PermissionUser.PleaseEnterPasswordAgain")
          )
        );
      } else if (value !== this.formData.password) {
        callback(new Error(this.$t("Permission.PermissionUser.twoPasswords")));
      } else {
        callback();
      }
    },
    getUser(name = "") {
      return new Promise((resolve) => {
        getUserListNoPage({ name: name }).then((res) => {
          resolve(
            res.data.map((item) => {
              return {
                id: item.id,
                name: item.name,
              };
            })
          );
        });
      });
    },
    // 搜索人员
    async remoteUser(query) {
      this.searchUserLoading = true;
      const filter = await this.getUser(query);
      if (filter && filter.length) {
        this.userList = filter;
      }
      this.searchUserLoading = false;
    },
    changeLeader(node) {
      console.log(node);
    },
  },
};
</script>
<style lang="scss">
.system-user-form {
  // padding-bottom: 24px;
  .relay-only-value {
    margin-bottom: 2px;
  }
  .default-form-item {
    display: block;
    height: 84px;
  }
}

.add {
  width: 30px;
  color: white;
  font-size: 20px;
  height: 32px;
  text-align: center;
  border-radius: 5px;
  border: 1px silver;
  background-color: #4787ff;
  margin-left: 10px;
  float: left;
  position: absolute;
  top: 0px;
  left: 121px;
}
.delete {
  background-color: rgb(194, 194, 194);
  left: 170px;
  font-size: 12px;
  border-radius: 10px;
}
</style>
<style lang="scss" scoped>
.el-form-item--small.el-form-item {
  margin-bottom: 25px;
}
</style>
